package cn.doitedu.zk.api;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @date: 2019/7/8
 * @site: www.doitedu.cn
 * @author: hunter.d 涛哥
 * @qq: 657270652
 * @description: zk客户端的各类数据操作api
 */
public class DataOperate {

    ZooKeeper zk = null;

    @Before
    public void init() throws Exception {
        zk = new ZooKeeper("spark01:2181,spark02:2181,spark03:2181", 2000, null);
    }


    /**
     * 创建znode
     */
    @Test
    public void testCreate() throws Exception {


        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);
        dout.writeInt(9999);
        byte[] data = bout.toByteArray();

        String s = zk.create("/taoge", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        System.out.println(s);

        zk.close();
    }


    /**
     * 获取znode的value数据
     */
    @Test
    public void getData() throws Exception {


        byte[] data = zk.getData("/taoge", false, null);

        ByteArrayInputStream in = new ByteArrayInputStream(data);
        DataInputStream din = new DataInputStream(in);

        int value = din.readInt();
        System.out.println(value);

        zk.close();
    }


    /**
     * 获得指定路径下的子节点
     * @throws Exception
     */
    @Test
    public void getChildren() throws Exception {


        List<String> lst = zk.getChildren("/", false);
        System.out.println(lst);


        zk.close();
    }


    /**
     * 修改一个节点的value值
     * @throws Exception
     */
    @Test
    public void setData() throws Exception {

        zk.setData("/taoge","我爱你，亲爱的涛".getBytes(),-1);

        byte[] data = zk.getData("/taoge", false, null);

        String s = new String(data, "UTF-8");
        System.out.println(s);

        zk.close();

    }


    /**
     * 删除一个znode
     * @throws Exception
     */
    @Test
    public void deleteNode() throws Exception {

        zk.delete("/taoge",-1);

        zk.close();

    }


    // TODO 删除一个拥有子节点的节点     -- 练习递归


}
